<template>
  <view class="main">
    <view class="ip-item" @click="forShow = true">
      <input type="text" placeholder="请选择类型" disabled placeholder-class="ip" v-model="typeName" />
      <image src="/static/icon/down.svg" mode="widthFix" />
      <view class="block"></view>
    </view>
    <view class="ip-item" @click="$goUrl(`/pages/forSale/pages/select1`)">
      <input type="text" placeholder="请选择所属行业" disabled placeholder-class="ip" v-model="industryName" />
      <image src="/static/icon/down.svg" mode="widthFix" />
      <view class="block"></view>
    </view>
    <view class="ip-item" @click="circleShowFun">
      <input type="text" placeholder="请选择关联圈子" disabled placeholder-class="ip" v-model="circleName" />
      <image src="/static/icon/down.svg" mode="widthFix" />
      <view class="block"></view>
    </view>
    <!-- <view class="ip-item" @click="showTime = true">
      <input
        type="text"
        placeholder="请选择有效时间"
        disabled
        placeholder-class="ip"
        v-model="time"
      />
      <image src="/static/icon/down.svg" mode="widthFix" />
      <view class="block"></view>
    </view> -->
    <view class="ip-item" style="display: flex;flex-direction: column;">
      <view class="ip-item" style="border: none;width: 100%;padding: 0;">
        <textarea style="" maxlength="300" v-model="postFormData.content" type="text" placeholder="禁止发布虚假、违规、违反广告法（投资理财、信贷）
等内容，如有违规，平台有权直接删除并封号处理。" placeholder-class="ip" class="text-area" />
        <view class="number">
          {{ descNumber + "/" + 300 }}
        </view>
      </view>
      <view class="up-box" style="display: flex;justify-content: flex-start;width: 100%;margin-bottom: 0;">
        <view class="upload">
          <ImageUpload @upload="upload" />
        </view>
        <!-- <view class="number">
          <text style="color: #0753fd">{{ imageNumber }}</text>/9
        </view> -->
      </view>
    </view>

    <view class="form-box">
      <view class="form" v-for="(item, index) in formList" :key="index">
        <view class="ip dispaly-center" :key="ipIndex" v-for="(ipt, ipIndex) in item.form" style="margin-bottom: 30rpx">
          <view class="f-name">{{ ipt.name }}</view>
          <input :type="ipt.type" placeholder="请填写" v-model="ipt.value" :maxlength="ipt.maxlength"
            placeholder-class="ip" />
        </view>
        <view class="close" @click="deleteServer(item, index)">
          <van-icon name="cross" size="20" color="#fff" />
        </view>
      </view>
    </view>
    <view class="add" @click="addServer">
      <van-button icon="plus" type="primary" block text="添加" plain color="#0753fd" />
    </view>
  </view>
  <view class="btns">
    <!-- v-if="type == 1" -->
    <Button @clickButton="submitMoney" :loading="loading" loading-text="发布中" text="发布" />
    <!-- <Button v-if="type == 2" @clickButton="submit" :loading="loading" loading-text="发布中"
      :text="'¥' + Number(commentFee).toFixed(2)" /> -->
  </view>

  <!-- 供需类型 -->
  <van-popup v-model:show="forShow" round position="bottom">
    <van-picker :columns-field-names="{ text: 'dictLabel', value: 'dictCode' }" :columns="typeList"
      @cancel="forShow = false" @confirm="onTypeConfirm" />
  </van-popup>

  <!-- 关联圈子 -->
  <van-popup v-model:show="circleShow" round position="bottom">
    <van-picker :columns-field-names="{ text: 'name', value: 'id' }" :columns="circleList" @cancel="circleShow = false"
      @confirm="onCircleConfirm" />
  </van-popup>

  <!-- 有效时间 -->
  <van-popup v-model:show="showTime" round position="bottom">
    <van-date-picker v-model="currentDate" title="选择有效日期" @confirm="timeConfirm" :min-date="minDate" />
  </van-popup>
</template>

<script setup>
import { reactive, ref, watch } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import {
  getWriteFillList,
  submitForSale,
  myCircle,
  proxy,
  postTrends,
  getCircleList,
} from "@/api/apiList";

// 获取配置
const commentFee = ref("");
const getConfig = async () => {
  const res = await proxy("commentFee");
  if (res.code == 200) {
    commentFee.value = res.data.commentFee;
  }
};
getConfig();

const postFormData = reactive({
  circleId: "", //	圈子id；
  subtype: "", // 类型
  industryId: "",
  industry: "",
  expireTime: "",
  content: "",
  images: "",
  products: [],
  source: "",
});

// 供需类型
const forShow = ref(false);
const typeList = ref([]);
const getWriteFillListData = async () => {
  const res = await getWriteFillList("/trends_sub_type");
  if (res.code == 200) {
    typeList.value = res.data;
  }
};

const typeName = ref("");
const onTypeConfirm = (data) => {
  postFormData.subtype = data.selectedOptions[0].dictCode;
  typeName.value = data.selectedOptions[0].dictLabel;
  forShow.value = false;
};

// 选择关联圈子
const circleShow = ref(false);
const circleList = ref([]);
const getMyCircle = async () => {
  const res = await getCircleList();
  if (res.code == 200) {
    circleList.value = res.data;
  }
};

const circleShowFun = () => {
  if (JSON.stringify(circleData.value) == "{}") {
    circleShow.value = true;
  }
};

const circleName = ref("");
const onCircleConfirm = (data) => {
  postFormData.circleId = data.selectedOptions[0].id;
  circleName.value = data.selectedOptions[0].name;
  circleShow.value = false;
};

// 有效时间
// 获取当前时间
const now = new Date();

// 获取年、月、日，并将它们转换为字符串
const year = now.getFullYear().toString();
const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1，并用padStart确保两位数字
const day = String(now.getDate()).padStart(2, "0"); // 用padStart确保两位数字
const currentDate = ref([year, month, day]);
const minDate = new Date();
const time = ref("");
const showTime = ref(false);
const timeConfirm = (data) => {
  postFormData.expireTime = data.selectedValues.join("-") + " 00:00:00";
  time.value = data.selectedValues.join("-");
  showTime.value = false;
};

// 产品图片
const upload = (data) => {
  postFormData.images = data.join(",");
}
const circleData = ref({});
const type = ref("");
onLoad((option) => {
  postFormData.source = option.source;
  if (option.source == 0) {
    postFormData.subtype = "";
  }
  type.value = option.type;
  console.log(option.data, "op");
  if (option.data) {
    circleData.value = option.data ? JSON.parse(option.data) : {};
    postFormData.circleId = circleData.value.id;
    circleName.value = circleData.value.name;
  }
  console.log(circleData.value, "circleData.value");
  getPreviousPageType();
  getWriteFillListData();
  getMyCircle();
});

// 上一页带回的数据
const industryName = ref("");
const getPreviousPageType = () => {
  uni.$on("getData", (data) => {
    if (data) {
      postFormData.industryId = data.data.id;
      postFormData.industry = data.data.name;
      industryName.value = data.data.name;
    }
  });
};

const formList = ref([
  {
    form: [
      {
        name: "产品/服务",
        maxlength: 999,
        type: "text",
        value: "",
        key: "name",
      },
      { name: "品牌", maxlength: 999, type: "text", value: "", key: "brand" },
      { name: "数量", maxlength: 999, type: "number", value: "", key: "num" },
    ],
  },
]);

const addServer = () => {
  formList.value.push({
    form: [
      {
        name: "产品/服务",
        maxlength: 999,
        type: "text",
        value: "",
        key: "name",
      },
      { name: "品牌", maxlength: 999, type: "text", value: "", key: "brand" },
      { name: "数量", maxlength: 999, type: "number", value: "", key: "num" },
    ],
  });
};

const deleteServer = (item, index) => {
  formList.value.splice(index, 1);
};

const formData = ref({
  community: "",
  desc: "",
});

// 监听输入的详情字数
const descNumber = ref(0);
watch(
  () => postFormData,
  () => {
    descNumber.value = postFormData.content.length;
  },
  { deep: true }
);

// 监听上窜图片数量
const imageNumber = ref(0);
watch(
  () => postFormData.images,
  () => {
    imageNumber.value = postFormData.images.split(",").length;
  },
  { deep: true }
);

const loading = ref(false);
const submit = async () => {
  const productList = ref([]);
  formList.value.forEach((item, index) => {
    productList.value.push({
      name: item.form[0].value,
      brand: item.form[1].value,
      num: item.form[2].value,
    });
  });
  postFormData.products = productList.value;
  const checkBool = check();
  if (checkBool) {
    loading.value = true;
    console.log(postFormData, "postFormData");
    const res = await submitForSale(postFormData);
    if (res.code == 200) {
      loading.value = false;
      uni.showToast({
        title: "发布成功",
        icon: "none",
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    }
  }
};

// 不付钱
const submitMoney = async () => {
  const productList = ref([]);
  formList.value.forEach((item, index) => {
    productList.value.push({
      name: item.form[0].value,
      brand: item.form[1].value,
      num: item.form[2].value,
    });
  });
  postFormData.products = productList.value;
  const checkBool = check();
  // loading.value = true;
  console.log(postFormData, "postFormData");
  if (!postFormData.subtype) {
    return uni.showToast({
      title: "请选择您发布的类型",
      icon: "none",
    });
  }
  if (!postFormData.industryId) {
    return uni.showToast({
      title: "请选择您发布的行业",
      icon: "none",
    });
  }
  if (!postFormData.circleId) {
    return uni.showToast({
      title: "请选择关联的圈子",
      icon: "none",
    });
  }
  let newPostFormData;
  if (postFormData.source == 0) {
    newPostFormData = Object.assign(postFormData, {
      type: type.value,
    });
  } else {
    newPostFormData = postFormData;
  }

  const res = await postTrends(newPostFormData);
  if (res.code == 200) {
    loading.value = false;
    uni.showToast({
      title: "发布成功",
      icon: "none",
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1000);
  }
};

const check = () => {
  const { circleId, subtype, industry, expireTime, content, images, products } =
    postFormData;
  if (!subtype) {
    uni.showToast({
      title: "请选择类型",
      icon: "none",
    });
    return false;
  }
  if (!industry) {
    uni.showToast({
      title: "请选择行业",
      icon: "none",
    });
    return false;
  }
  if (!circleId) {
    uni.showToast({
      title: "请选择关联圈子",
      icon: "none",
    });
    return false;
  }

  // if (!expireTime) {
  //   uni.showToast({
  //     title: "请选择有效时间",
  //     icon: "none",
  //   });
  //   return false;
  // }
  if (!content) {
    uni.showToast({
      title: "请填写内容",
      icon: "none",
    });
    return false;
  }
  // if (!images) {
  //   uni.showToast({
  //     title: "请上传产品图片",
  //     icon: "none",
  //   });
  //   return false;
  // }
  for (let index = 0; index < products.length; index++) {
    if (!products[index].name) {
      uni.showToast({
        title: "请填写产品名称",
        icon: "none",
      });
      return false;
    }
    if (!products[index].brand) {
      uni.showToast({
        title: "请填写产品品牌",
        icon: "none",
      });
      return false;
    }
    if (!products[index].num) {
      uni.showToast({
        title: "请填写产品数量",
        icon: "none",
      });
      return false;
    }
  }

  return true;
};
</script>

<style lang="scss" scoped>
.main {
  padding: 50rpx 50rpx 200rpx 50rpx;

  .up-box {
    margin-bottom: 20rpx;

    .upload {
      margin-bottom: 24rpx;
    }

    .number {
      color: #bbbbbb;
      font-size: 22rpx;
    }
  }
}

.btns {
  padding: 30rpx;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
}

.add {
  margin-top: 40rpx;
}

.form-box {
  .form {
    box-sizing: border-box;
    border: 2rpx solid #0753fd;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    padding: 40rpx;
    position: relative;

    .close {
      padding: 14rpx;
      position: absolute;
      top: 0;
      right: 0;
      border-radius: 0px 16rpx 0px 8rpx;
      opacity: 0.5;
      background: #000000;
    }

    .ip {
      .f-name {
        flex: 1.5;
        font-family: PingFang SC Medium;
        font-size: 32rpx;
        color: #111111;
      }

      input {
        flex: 4;
        font-size: 32rpx;
      }
    }
  }
}
</style>
